// stores/user.ts
import { defineStore } from 'pinia'

const STORAGE_KEY = 'user_profile_v1'

type UserState = {
  avatar: string
  username: string
  gender: 'male' | 'female' | '未知'
  age: string
}

function loadFromLocal(): Partial<UserState> | null {
  try {
    const raw = localStorage.getItem(STORAGE_KEY)
    return raw ? JSON.parse(raw) : null
  } catch {
    return null
  }
}

function saveToLocal(state: UserState) {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(state))
  } catch {}
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    avatar: 'https://ku-sheet-server.baidu-int.com/uploader/f/EUqwD6ufcdOJDAbP.png?accessToken=eyJhbGciOiJIUzI1NiIsImtpZCI6ImRlZmF1bHQiLCJ0eXAiOiJKV1QifQ.eyJleHAiOjE3NTY2MzgwOTgsImZpbGVHVUlEIjoiNlo0SXVSMTB1ZGlra0JOdSIsImlhdCI6MTc1NjYzNzQ5OCwiaXNzIjoidXBsb2FkZXJfYWNjZXNzX3Jlc291cmNlIiwidXNlcklkIjoxMDAwMDEyOTY5M30.R4qUoZ07NOt6kKD8Yc1sHLB9EE9cP3z28RTsbm-28Bs',
    username: '唐怡',
    gender: 'female',
    age: '22',
    ...(loadFromLocal() || {})
  }),
  actions: {
    updateAvatar(newAvatar: string) {
      this.avatar = newAvatar
      saveToLocal(this.$state)
    },
    updateUserInfo(info: Partial<UserState>) {
      if (info.username !== undefined) this.username = info.username
      if (info.gender   !== undefined) this.gender   = info.gender as UserState['gender']
      if (info.age      !== undefined) this.age      = info.age
      if (info.avatar   !== undefined) this.avatar   = info.avatar
      saveToLocal(this.$state)
    }
  }
})
